package com.example.mydemo.service.impl;

import com.example.mydemo.converter.Converter;
import com.example.mydemo.dao.TestRepository;
import com.example.mydemo.dto.DTO;
import com.example.mydemo.entity.Test;
import com.example.mydemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class Student implements StudentService {
    @Autowired
    private TestRepository testRepository;

    @Override
    public DTO getStudentById(Integer id) {
        Test test = testRepository.findById(id).orElseThrow(() -> new RuntimeException("没有此用户"));
        return Converter.convert(test);
    }

    @Override
    public DTO createStudent(Test test) {
        Test test1 = testRepository.save(test);
        return Converter.convert(test1);
    }

    @Override
    public void deleteStudent(Integer id) {
        testRepository.findById(id).orElseThrow(() -> new RuntimeException("没有此用户"));
        testRepository.deleteById(id);
    }

    @Override
    public List<Test> findbyName(String name) {
        List<Test> test = testRepository.findByName(name);
        return test;
    }

    @Override
    public DTO updateStudent(Integer id, Test test) {
        Test test1 = testRepository.findById(id).orElseThrow(() -> new RuntimeException("没有此用户"));
        if(StringUtils.hasLength(test.getName())&&!test.getName().equals(test1.getName())){
            test1.setName(test.getName());
        }
        if(StringUtils.hasLength(test.getAge())&&!test.getAge().equals(test1.getAge())){
            test1.setAge(test.getAge());
        }
        if(StringUtils.hasLength(test.getSex())&&!test.getSex().equals(test1.getSex())){
            test1.setSex(test.getSex());
        }
        System.out.println(test1);
        Test test2 = testRepository.save(test1);
        return Converter.convert(test2);
    }
}
